package com.yonyou.brigade.third_parties.fanscar.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.basic_init.model.BriChannel;
import com.yonyou.brigade.basic_init.service.IBaseDocService;
import com.yonyou.brigade.basic_init.service.IBriChannelService;
import com.yonyou.brigade.basic_init.service.IUserCenterService;
import com.yonyou.brigade.third_parties.fanscar.constants.FanscarConstants;
import com.yonyou.brigade.third_parties.fanscar.model.FanscarConfig;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarPublicService;
import com.yonyou.brigade.third_parties.fanscar.service.IFanscarUserService;
import com.yonyou.brigade.third_parties.fanscar.util.UserConvertUtil;
import com.yonyou.brigade.util.HttpClientUtil;
import com.yonyou.brigade.util.operateutil.DateUtils;
import com.yonyou.ybzboot.starter.common.cipher.Base64Util;
import com.yonyou.ybzboot.starter.common.exception.BusinessException;
import com.yonyou.ybzboot.starter.common.exception.CustomException;
import com.yonyou.ybzboot.starter.common.util.StringUtil;
import com.yonyou.ybzboot.uc.dto.UcUserDto;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 *
 * @author houyb
 * @since 2019-02-28
 */
@Service
public class FanscarPublicServiceImpl implements IFanscarPublicService {

    @Value("${fanscar.url}")
    private String baseUrl;

    @Value("${fanscar.apiUrl}")
    private String apiUrl;

    @Autowired
    @Qualifier("briChannelServiceImpl")
    private IBriChannelService channelService;

    @Autowired
    @Qualifier("userCenterServiceImpl")
    private IUserCenterService iUserCenterService;

    @Autowired
    private IFanscarUserService fanscarUserService;

    private final String APPLICATION_NUMBER = "applicationNumber";


    @Autowired
    private IBaseDocService baseDocService;

    private static final Logger logger = LoggerFactory.getLogger(FanscarPublicServiceImpl.class);

    @Override
    public JSONObject pushApplayOrder(BriChannel channel, String tenant, String orgPk, JSONObject applyOrderJson) {
        JSONObject summaryResult = new JSONObject();
        FanscarConfig fanscarConfig = (FanscarConfig) channelService.getChannelConfig(tenant, ChannelEnum.FANSCAR.getName(), orgPk, new FanscarConfig());

        logger.info("泛嘉国际申请单信息:" + applyOrderJson.toString());
        logger.info("开始拼装同步申请单数据");
        JSONObject data = processApplyData(channel, applyOrderJson, tenant, Integer.parseInt(fanscarConfig.getRedundantDays()), fanscarConfig);

        if (data.getString("msg") != null && !"".equals(data.getString("msg"))) {
            summaryResult.put("success", false);
            summaryResult.put("msg", data.getString("msg"));
            return summaryResult;
        }
        JSONArray flightArr = data.getJSONArray("flightArr");
        JSONArray hotelArr = data.getJSONArray("hotelArr");
        JSONArray trainArr = data.getJSONArray("trainArr");
        data.remove("flightArr");
        data.remove("hotelArr");
        data.remove("trainArr");
        //泛嘉国际返回结果
        String result = "";
        Map<String, String> headers = new HashMap<>();
        String token = getToken(fanscarConfig);
        headers.put("Authorization", "bearer " + token);
        //有行程明细
        if (!CollectionUtils.isEmpty(flightArr) || !CollectionUtils.isEmpty(hotelArr) || !CollectionUtils.isEmpty(trainArr)) {
            if (flightArr.size() > 0) {
                data.put("Trips", flightArr);
                String jsonStr = data.toJSONString();
                logger.info("发送泛嘉国际机票申请单信息:" + jsonStr);
                result = HttpClientUtil.post(apiUrl + FanscarConstants.URL_APPLYORDER_FLIGHT, headers, null, jsonStr);
                logger.info("请求泛嘉国际机票申请单返回信息:" + result);
                if (!StringUtil.isEmpty(result) && JSONObject.parseObject(result) != null && JSONObject.parseObject(result).getJSONArray("data").size() == 0) {
                    logger.info("泛嘉国际机票申请单推送成功!");
                } else {
                    logger.error("泛嘉国际机票申请单推送失败! " + result);
                    summaryResult.put("success", false);
                    summaryResult.put("msg", " 泛嘉国际机票申请单推送失败! ");
                    return summaryResult;
                }
            }
            if (hotelArr.size() > 0) {
                data.put("Trips", hotelArr);
                String jsonStr = data.toJSONString();
                logger.info("发送泛嘉国际酒店申请单信息:" + jsonStr);
                result = HttpClientUtil.post(apiUrl + FanscarConstants.URL_APPLYORDER_HOTEL, headers, null, jsonStr);
                logger.info("请求泛嘉国际酒店申请单返回信息:" + result);
                if (!StringUtil.isEmpty(result) && JSONObject.parseObject(result) != null && JSONObject.parseObject(result).getJSONArray("data").size() == 0) {
                    logger.info("泛嘉国际酒店申请单推送成功!");
                } else {
                    logger.error("泛嘉国际酒店申请单推送失败! " + result);
                    summaryResult.put("success", false);
                    summaryResult.put("msg", " 泛嘉国际酒店申请单推送失败! ");
                    return summaryResult;
                }
            }
            if (trainArr.size() > 0) {
                data.put("Trips", trainArr);
                String jsonStr = data.toJSONString();
                logger.info("发送泛嘉国际火车申请单信息:" + jsonStr);
                result = HttpClientUtil.post(apiUrl + FanscarConstants.URL_APPLYORDER_TRAIN, headers, null, jsonStr);
                logger.info("请求泛嘉国际火车申请单返回信息:" + result);
                if (!StringUtil.isEmpty(result) && JSONObject.parseObject(result) != null && JSONObject.parseObject(result).getJSONArray("data").size() == 0) {
                    logger.info("泛嘉国际火车申请单推送成功!");
                } else {
                    logger.error("泛嘉国际火车申请单推送失败! " + result);
                    summaryResult.put("success", false);
                    summaryResult.put("msg", " 泛嘉国际火车申请单推送失败! ");
                    return summaryResult;
                }
            }
        } else {
            logger.info("没有行程明细! ");
            summaryResult.put("success", false);
            summaryResult.put("msg", " 没有行程明细! ");
        }
        summaryResult.put("success", true);
        return summaryResult;
    }

    /**
     * 申请单关闭
     *
     * @param applicationNumber 申请单号
     * @param channel     泛嘉配置信息
     * @return
     */
    @Override
    public List closeApplyOrder(String applicationNumber, BriChannel channel) {
        JSONArray result = new JSONArray();
        String channelConfig = channel.getConfig();
        FanscarConfig fanscarConfig = JSONObject.parseObject(channelConfig, FanscarConfig.class);
        if (null != fanscarConfig) {
            String token = "";
            try {
                token = getToken(fanscarConfig);
            } catch (Exception e) {
                logger.error("泛嘉商旅关闭申请单时获取认证失败");
            }
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "bearer " + token);

            JSONObject paramJSON = new JSONObject();
            paramJSON.put(APPLICATION_NUMBER, applicationNumber);

            String cancelFlightResult = HttpClientUtil.post(apiUrl + FanscarConstants.CANCEL_FLIGHT_APPLICATION, headers, null, paramJSON.toJSONString());
            String cancelHotelResult = HttpClientUtil.post(apiUrl + FanscarConstants.CANCEL_HOTEL_APPLICATION, headers, null, paramJSON.toJSONString());
            String cancelTrainResult = HttpClientUtil.post(apiUrl + FanscarConstants.CANCEL_TRAIN_APPLICATION, headers, null, paramJSON.toJSONString());

            result.addAll(Optional.ofNullable(JSON.parseObject(cancelFlightResult).getJSONArray("data")).orElse(new JSONArray()));
            result.addAll(Optional.ofNullable(JSON.parseObject(cancelHotelResult).getJSONArray("data")).orElse(new JSONArray()));
            result.addAll(Optional.ofNullable(JSON.parseObject(cancelTrainResult).getJSONArray("data")).orElse(new JSONArray()));
        }
        return result;
    }

    /**
     * 获取Token
     *
     * @param fanscarConfig 配置信息
     * @since :2019-02-28
     */
    @Override
    public String getToken(FanscarConfig fanscarConfig) {
        String encodeAuth = null;
        try {
            encodeAuth = Base64Util.encode(fanscarConfig.getClientId() + ":" + fanscarConfig.getClientSecret());
        } catch (Exception e) {
            logger.error("Authorization编码错误");
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "basic " + encodeAuth);
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "password");
        params.put("username", fanscarConfig.getUsername());
        params.put("password", fanscarConfig.getPassword());
        String httpResultString = HttpClientUtil.postForm(baseUrl + FanscarConstants.GET_TOKEN_URI, headers, null, params);
        JSONObject httpResultJson = JSONObject.parseObject(httpResultString);
        String accessToken = httpResultJson.getString("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            throw new CustomException("调用泛嘉商旅获取认证失败");
        }
        return accessToken;
    }

    /**
     * 获取H5跳转Token
     *
     * @param employeeId    创建用户的员工ID
     * @param fanscarConfig 泛嘉开通信息
     * @return String H5跳转token
     * @since : 2019-02-28
     */
    @Override
    public String getH5Token(String employeeId, FanscarConfig fanscarConfig) {
        String encodeAuth = null;
        try {
            encodeAuth = Base64Util.encode(fanscarConfig.getClientId() + ":" + fanscarConfig.getClientSecret());
        } catch (Exception e) {
            logger.error("Authorization编码错误");
        }
        Map<String, String> headers = new HashMap<>();
        headers.put("Authorization", "basic " + encodeAuth);
        Map<String, String> params = new HashMap<>();
        params.put("grant_type", "password");
        params.put("username", employeeId);
        String httpResultString = HttpClientUtil.postForm(baseUrl + FanscarConstants.GET_TOKEN_URI, headers, null, params);
        JSONObject httpResultJson = JSONObject.parseObject(httpResultString);
        String accessToken = httpResultJson.getString("access_token");
        if (StringUtils.isEmpty(accessToken)) {
            throw new CustomException("调用泛嘉商旅获取认证失败");
        }
        return accessToken;
    }

    /**
     * 转换companion中的字符
     *
     * @param companion
     * @return
     */
    public static String convertTraveler(String companion) {
        String convertStr = companion;
        if (companion.contains("（")) {
            convertStr = companion.replaceAll("（", ":");
        }
        if (companion.contains("(")) {
            convertStr = convertStr.replaceAll("\\(", ":");
        }
        if (companion.contains("）")) {
            convertStr = convertStr.replaceAll("）", "");
        }
        if (companion.contains(")")) {
            convertStr = convertStr.replaceAll("\\)", "");
        }
        if (companion.contains("，")) {
            convertStr = convertStr.replaceAll("，", ",");
        }
        if (companion.contains("、")) {
            convertStr = convertStr.replaceAll("、", ",");
        }
        return convertStr;
    }


    /**
     * 拼装申请单数据
     *
     * @param applyOrderJson
     * @param tenant
     * @param redundantDays
     * @return
     */
    private JSONObject processApplyData(BriChannel briChannel, JSONObject applyOrderJson, String tenant, int redundantDays, FanscarConfig fanscarConfig) {
        JSONObject applyData = new JSONObject();
        JSONObject nodeBusinessTrip = applyOrderJson;
        JSONObject special = nodeBusinessTrip.getJSONObject("special");
        if (StringUtil.isNotEmpty(nodeBusinessTrip.getString("billNum"))) {
            applyData.put("ApplicationNumber", nodeBusinessTrip.getString("billNum"));
        } else {
            applyData.put("ApplicationNumber", special.getString("applayNumber"));
        }
        String osType = special.getString("openType");
        //员工ID
        String userId = nodeBusinessTrip.getString("userId");
        List<String> list = new ArrayList<>();
        list.add(userId);
        List<UcUserDto> users = iUserCenterService.getCompleteUcUserDtoByUserid(list, tenant);
        if (users.size() > 0) {
            // 检查申请单创建人是否已同步泛嘉对应进行新增或更新泛嘉用户
            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                fanscarUserService.insertOrUpdateEmployee(UserConvertUtil.convertToFanscarUser(users.get(0)), fanscarConfig);
            }
            applyData.put("EmployeeId", users.get(0).getPersonCode());
        } else {
            applyData.put("msg", "找不到用户:" + userId);
            return applyData;
        }
        //实际出行人
        List<String> companionList = new ArrayList<>();
        boolean success = getPassenger(briChannel, companionList, nodeBusinessTrip, tenant,users.get(0).getPersonCode(), osType, fanscarConfig);
        if (!success) {
            applyData.put("msg", "查询实际出行人出错" + nodeBusinessTrip);
            return applyData;
        }

        SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = nodeBusinessTrip.getDate("startDate");
        Date endDate = nodeBusinessTrip.getDate("endDate");
        String departureStartDate = DateUtils.plusDay(-redundantDays, startDate);
        String departureEndDate = DateUtils.plusDay(redundantDays, endDate);
        // 酒店入住离店时间处理
        String hotelCheckInEndDate = departureStartDate;
        String hotelCheckOutStartDate = departureEndDate;
        if (!DateUtils.plusDay(1 - redundantDays, startDate).equals(departureEndDate)) {
            // 酒店入住结束时间
            hotelCheckInEndDate = DateUtils.plusDay(redundantDays - 1, endDate);
            // 酒店离店开始时间
            hotelCheckOutStartDate = DateUtils.plusDay(1 - redundantDays, startDate);
        }

        String expireDate = f.format(endDate);
        applyData.put("ExpiredTime", expireDate + " 23:59:59");

        //费用承担信息
        processCostInfo(tenant, userId, osType, applyData, briChannel, nodeBusinessTrip);

        //状态（0：禁用；1：启用，默认为启用）
        applyData.put("Status", 1);
        // 单据详情
        JSONArray travelList = nodeBusinessTrip.getJSONArray("nodeBusinessTravelList");
        //行程信息
        JSONArray flightArr = new JSONArray();
        JSONArray hotelArr = new JSONArray();
        JSONArray trainArr = new JSONArray();
        JSONObject oldCityCodes = special.getJSONObject("cityCodes");
        JSONObject codes = splitCityCodes(oldCityCodes,travelList);
        if (travelList != null && travelList.size() > 0){
            for (int i = 0; i < travelList.size(); i++) {
                JSONObject travel = travelList.getJSONObject(i);
                String tripWay = travel.getString("tripWay");
                JSONObject applyOrderJourney = new JSONObject();

                if ("飞机".equals(tripWay)) {
                    String tripType = travel.getString("tripType");
                    if ("RT".equals(tripType)) {
                        applyOrderJourney.put("ReturnStartDate", departureStartDate);
                        applyOrderJourney.put("ReturnEndDate", departureEndDate);
                    }
                    if (codes.getBooleanValue("isRT")) {
                        applyOrderJourney.put("TripType", 2);
                    }
                    applyOrderJourney.put("DepartureStartDate", departureStartDate);
                    applyOrderJourney.put("DepartureEndDate", departureEndDate);
                    applyOrderJourney.put("PassengerIds", String.join(",", companionList));
                    applyOrderJourney.put("FlightType", 1);
                    if (StringUtils.isNotBlank(travel.getString("fromCity"))) {
                        String cityName = travel.getString("fromCity").split("-")[0];
                        applyOrderJourney.put("DepartureCityCodes", oldCityCodes.getString(cityName));
                    }
                    if (StringUtils.isNotBlank(travel.getString("toCity"))) {
                        String cityName = travel.getString("toCity").split("-")[0];
                        applyOrderJourney.put("ArrivalCityCodes", oldCityCodes.getString(cityName));
                    }
                    flightArr.add(applyOrderJourney);
                } else if ("火车".equals(tripWay)) {
                    if (codes.getBooleanValue("isRT")) {
                        applyOrderJourney.put("TripType", 2);
                        applyOrderJourney.put("ReturnStartDate", departureStartDate);
                        applyOrderJourney.put("ReturnEndDate", departureEndDate);
                    }
                    applyOrderJourney.put("DepartureStartDate", departureStartDate);
                    applyOrderJourney.put("DepartureEndDate", departureEndDate);
                    applyOrderJourney.put("PassengerIds", String.join(",", companionList));
                    if (StringUtils.isNotBlank(travel.getString("fromCity"))) {
                        applyOrderJourney.put("DepartureCityCodes", oldCityCodes.getString(travel.getString("fromCity")));
                    }
                    if (StringUtils.isNotBlank(travel.getString("toCity"))) {
                        applyOrderJourney.put("ArrivalCityCodes", oldCityCodes.getString(travel.getString("toCity")));
                    }
                    applyOrderJourney.put("CostType", 1);
                    trainArr.add(applyOrderJourney);
                }

                //酒店入住信息
                if (!departureStartDate.equals(departureEndDate) && travel.getBigDecimal("yghotelcost") != null && travel.getBigDecimal("yghotelcost").compareTo(new BigDecimal(0)) > 0) {
                    applyOrderJourney.put("CheckInStartDate", departureStartDate);
                    applyOrderJourney.put("CheckInEndDate", hotelCheckInEndDate);
                    applyOrderJourney.put("CheckOutStartDate", hotelCheckOutStartDate);
                    applyOrderJourney.put("CheckOutEndDate", departureEndDate);
                    applyOrderJourney.put("PassengerIds", String.join(",", companionList));
                    applyOrderJourney.put("CostType", 1);
                    // DestinationCityCodes	string	否	目的地城市代码集合，以半角逗号隔开（只支持地级市）
                    if (StringUtils.isNotBlank(travel.getString("defitem1"))) {
                        applyOrderJourney.put("DestinationCityCodes", oldCityCodes.getString(travel.getString("defitem1")));
                    }
                    // Limit	decimal	否	额度
                    if (travel.getBigDecimal("hotelstandard") != null && travel.getBigDecimal("hotelstandard").doubleValue() > 0) {
                        applyOrderJourney.put("Limit", travel.getDouble("hotelstandard").doubleValue());
                    }
                    //同行最高标准出行人
                    String leader = nodeBusinessTrip.getString("defitem1");
                    if (StringUtils.isNotBlank(leader)) {
                        String[] split = leader.split(",");
                        if (split.length > 0) {
                            String leaderId = split[0];
                            List<UcUserDto> leaders = null;
                            if ("nc".equals(osType)) {
                                leaders = iUserCenterService.getCompleteUcUserByPersonIds(Arrays.asList(leaderId), tenant);
                            } else {
                                leaders = iUserCenterService.getCompleteUcUserDtoByUserid(Arrays.asList(leaderId), tenant);
                            }
                            if (leaders != null && leaders.size() > 0) {
                                if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                                    fanscarUserService.insertOrUpdateEmployee(UserConvertUtil.convertToFanscarUser(leaders.get(0)), fanscarConfig);
                                }
                                applyData.put("ReferencedEmployeeId", leaders.get(0).getPersonCode());
                            } else {
                                logger.info("用户中心未找到同行最高标准出行人:" + leader);
                            }
                        }
                    }
                    hotelArr.add(applyOrderJourney);
                }
            }

        } else {
            applyData.put("msg", "没有行程明细");
            return applyData;
        }
        if (flightArr.size() <= 0 && hotelArr.size() <= 0 && trainArr.size() <= 0) {
            applyData.put("msg", "没有符合条件的行程明细");
            return applyData;
        }
        applyData.put("flightArr", flightArr);
        applyData.put("hotelArr", hotelArr);
        applyData.put("trainArr", trainArr);

        return applyData;
    }

    /**
     * 同步费用归属信息
     * @param tenant
     * @param userId
     * @param openType
     * @param applyData
     * @param channel
     * @param nodeBusinessTrip
     */
    private void processCostInfo(String tenant, String userId, String openType, JSONObject applyData, BriChannel channel, JSONObject nodeBusinessTrip) {
        if (channel != null && channel.getSyncCostInfo() != 0) {
            //费用承担部门
            String assumeDept = nodeBusinessTrip.getString("assumeDept");
            String[] assumeDeptArr = assumeDept != null ? assumeDept.split(",") : null;

            //费用承担单位
            String assumeOrg = nodeBusinessTrip.getString("assumeOrg");
            String[] assumeOrgArr = assumeOrg != null ? assumeOrg.split(",") : null;

            //费用项目
            String costProject = nodeBusinessTrip.getString("costProject");
            String[] costProjectArr = costProject != null ? costProject.split(",") : null;

            String assumeDeptValue = "";
            String assumeOrgValue = "";
            String assumeProjectValue = "";
            switch (channel.getSyncCostInfo()) {
                //传名称
                case 1:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        if (assumeDeptArr.length > 1){
                            assumeDeptValue = assumeDeptArr[1];

                        }else {
                            Map<String, String> deptInfo = baseDocService.getDeptByOsType(tenant, userId ,assumeDeptArr[0], openType);
                            assumeDeptValue = deptInfo != null ? deptInfo.get("name") : "";
                        }
                    }

                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        if (assumeOrgArr.length > 1){
                            assumeOrgValue = assumeOrgArr[1];
                        }else {
                            Map<String, String> orgInfo = baseDocService.getOrgByOsType(tenant, userId, assumeOrgArr[0], openType);
                            assumeOrgValue = orgInfo != null ? orgInfo.get("name") : "";
                        }
                    }

                    if (costProjectArr != null && costProjectArr.length > 0){
                        if (costProjectArr.length > 1){
                            assumeProjectValue = costProjectArr[1];
                        }else {
                            Map<String, String> projectInfo = baseDocService.getInOutProjectByOsType(tenant, userId, costProjectArr[0], openType);
                            assumeProjectValue = projectInfo != null ? projectInfo.get("name") : "";
                        }
                    }
                    break;
                //传pk
                case 2:
                    if (assumeDeptArr != null && assumeDeptArr.length > 0){
                        assumeDeptValue = assumeDeptArr[0];
                    }

                    if (assumeOrgArr != null && assumeOrgArr.length > 0){
                        assumeOrgValue = assumeOrgArr[0];
                    }

                    if (costProjectArr != null && costProjectArr.length > 0){
                        assumeProjectValue = costProjectArr[0];
                    }
                    break;
                default:
                    break;
            }

            if (assumeOrgArr != null && assumeOrgArr.length > 0) {
                applyData.put("TopDepartment", assumeOrgValue);
            }

            if (assumeDeptArr != null && assumeDeptArr.length > 0) {
                applyData.put("CostDepartment", assumeDeptValue);
            }
        }
    }


    private JSONObject splitCityCodes(JSONObject cityCodes, JSONArray travelList) {
        JSONObject result = new JSONObject();
        List<String> airFromCity = new ArrayList<>();
        List<String> trainFromCity = new ArrayList<>();
        List<String> airToCity = new ArrayList<>();
        List<String> trainToCity = new ArrayList<>();
        List<String> hotelCity = new ArrayList<>();
        boolean isRT = false;
        if (travelList != null && travelList.size() > 0) {
            for (int i = 0; i < travelList.size(); i++) {
                JSONObject travel = travelList.getJSONObject(i);
                String tripType = travel.getString("tripType");
                if ("RT".equals(tripType)){
                    isRT = true;
                }
                String tripWay = travel.getString("tripWay");
                String fromCityName = travel.getString("fromCity");
                String toCityName = travel.getString("toCity");
                if ("飞机".equals(tripWay)){
                    if (StringUtils.isNotBlank(fromCityName)){
                        String cityName = fromCityName.split("-")[0];
                        airFromCity.add(cityCodes.getString(cityName));
                    }
                    if (StringUtils.isNotBlank(toCityName)){
                        String cityName = toCityName.split("-")[0];
                        airToCity.add(cityCodes.getString(cityName));
                    }
                }
                if ("火车".equals(tripWay)){
                    trainFromCity.add(cityCodes.getString(fromCityName));
                    trainToCity.add(cityCodes.getString(toCityName));
                }
                if (travel.getBigDecimal("yghotelcost") != null && travel.getBigDecimal("yghotelcost").compareTo(new BigDecimal(0)) > 0){
                    String cityName = travel.getString("");
                    hotelCity.add(cityCodes.getString(cityName));
                }
            }
            result.put("airFromCity",String.join(",",airFromCity));
            result.put("trainFromCity",String.join(",",trainFromCity));
            result.put("airToCity",String.join(",",airToCity));
            result.put("trainToCity",String.join(",",trainToCity));
            result.put("hotelCity",String.join(",",hotelCity));
            if (isRT){
                result.put("isRT",isRT);
            }
            return result;
        }
        return null;
    }
    /**
     * 获取实际出行人
     * @param companionList
     * @param tenant
     * @param pcode
     * @return
     */
    private boolean getPassenger(BriChannel briChannel, List<String> companionList, JSONObject nodeBusinessTrip, String tenant, String pcode, String opentType, FanscarConfig fanscarConfig){
        // 报账3.18新增市级出行人字段格式为{pk;pk}
        String actualPedestrian = nodeBusinessTrip.getString("actualPedestrian");

        // 旧的实际出行人为手输格式，支持格式  张三（17934125896），李四（14536897562）
        String companion = nodeBusinessTrip.getString("companion");

        if (StringUtils.isNotBlank(actualPedestrian)){
            actualPedestrian = convertTraveler(actualPedestrian);
            String[] split = actualPedestrian.split(";");
            List<String> personIds = new ArrayList<>();
            for (String str : split) {
                if (str.split(",").length>0){
                    personIds.add(str.split(",")[0]);
                }
            }
            List<UcUserDto> companionUser = null;
            if ("nc".equals(opentType)){
                companionUser = iUserCenterService.getCompleteUcUserByPersonIds(personIds,tenant);
            }else {
                companionUser = iUserCenterService.getCompleteUcUserDtoByUserid(personIds,tenant);
            }

            if (companionUser != null && companionUser.size() == personIds.size()){
                for (UcUserDto ucUserDto : companionUser) {
                    if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                        fanscarUserService.insertOrUpdateEmployee(UserConvertUtil.convertToFanscarUser(ucUserDto), fanscarConfig);
                    }
                    companionList.add(ucUserDto.getPersonCode());
                }
            }else {
                logger.info("用户中心未找到实际出行人:" + personIds.toString());
                //TODO 用户中心未找到人员时同步erp用户，再次查找。
                throw new BusinessException("用户中心未找到部分实际出行人");
            }
        }
        UcUserDto sscUser = iUserCenterService.getCompleteUcUserDtoByPersonCode(pcode, tenant);
        if (StringUtils.isNotBlank(companion)) {
            companion = convertTraveler(companion);
            if (!StringUtils.isEmpty(companion) && companion.contains(":")) {
                String[] split = companion.split(",");
                for (String str : split) {
                    String[] strings = str.split(":");
                    //如果手输实际出行人和制单人名字一致，则忽略
                    if (split.length == 1 && strings[0].equals(sscUser.getUserName())){
                        continue;
                    }
                    if (strings.length > 1){
                        String phoneNo = strings[1];
                        UcUserDto companionUser = iUserCenterService.getCompleteUcUserDtoByPhone(phoneNo, tenant);
                        if (companionUser != null && StringUtils.isNotEmpty(companionUser.getPersonCode())) {
                            if (BriChannel.SYNCUSER == briChannel.getSyncUser()) {
                                fanscarUserService.insertOrUpdateEmployee(UserConvertUtil.convertToFanscarUser(companionUser), fanscarConfig);
                            }
                            companionList.add(companionUser.getPersonCode());
                        } else {
                            String msg = "用户中心未找到或部分未找到实际出行人companion:" + phoneNo;
                            logger.info(msg);
                            return false;
                        }

                    }else {
                        logger.error("为传递手机号：" + str);
                    }
                }
            }
        }

        if(CollectionUtils.isEmpty(companionList)) {
            companionList.add(pcode);
        }
        return true;
    }
}
